#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

// 需要修复的文件列表
const filesToFix = [
  'backend/src/services/xlayer.service.ts',
  'backend/src/contracts/xlayer-contract.ts',
  'simple-create.ts',
  'frontend/src/hooks/useXLayerWallet.ts'
];

// 修复模式
const fixes = [
  {
    // 移除默认的RPC URL
    pattern: /process\.env\.XLAYER_RPC_URL\s*\|\|\s*['"][^'"]*['"]/g,
    replacement: 'process.env.XLAYER_RPC_URL'
  },
  {
    // 移除默认的NEXT_PUBLIC_XLAYER_RPC_URL  
    pattern: /process\.env\.NEXT_PUBLIC_XLAYER_RPC_URL\s*\|\|\s*['"][^'"]*['"]/g,
    replacement: 'process.env.NEXT_PUBLIC_XLAYER_RPC_URL'
  }
];

// 添加验证逻辑的模式
const validationPatterns = [
  {
    // 在provider创建之前添加验证
    pattern: /(const provider = new ethers\.JsonRpcProvider\(\s*)(process\.env\.XLAYER_RPC_URL)(\s*[,)];?\s*)/g,
    replacement: (match, p1, p2, p3) => {
      return `if (!${p2}) {\n      throw new Error('XLAYER_RPC_URL environment variable is required');\n    }\n    ${p1}${p2}${p3}`;
    }
  }
];

console.log('开始修复项目中的RPC URL默认值...\n');

filesToFix.forEach(filePath => {
  const fullPath = path.join(__dirname, filePath);
  
  if (!fs.existsSync(fullPath)) {
    console.log(`跳过不存在的文件: ${filePath}`);
    return;
  }
  
  console.log(`修复文件: ${filePath}`);
  
  let content = fs.readFileSync(fullPath, 'utf8');
  let modified = false;
  
  // 应用基本修复
  fixes.forEach(fix => {
    const oldContent = content;
    content = content.replace(fix.pattern, fix.replacement);
    if (content !== oldContent) {
      modified = true;
      const matches = oldContent.match(fix.pattern);
      console.log(`  - 移除了 ${matches ? matches.length : 0} 个默认RPC URL`);
    }
  });
  
  // 应用验证逻辑（仅对TypeScript文件）
  if (filePath.endsWith('.ts') || filePath.endsWith('.tsx')) {
    validationPatterns.forEach(validation => {
      const oldContent = content;
      content = content.replace(validation.pattern, validation.replacement);
      if (content !== oldContent) {
        modified = true;
        console.log(`  - 添加了环境变量验证`);
      }
    });
  }
  
  if (modified) {
    fs.writeFileSync(fullPath, content, 'utf8');
    console.log(`  ✅ 文件已更新`);
  } else {
    console.log(`  ℹ️  文件无需修改`);
  }
  console.log('');
});

console.log('修复完成！\n');
console.log('注意事项:');
console.log('1. 请确保在生产环境中设置了正确的 XLAYER_RPC_URL 环境变量');
console.log('2. 请确保在前端环境中设置了正确的 NEXT_PUBLIC_XLAYER_RPC_URL 环境变量');
console.log('3. 运行测试确保所有功能正常工作');
